package com.artmall.manager.common.aspect;


import com.artmall.common.utils.IPUtils;
import com.artmall.manager.common.annotation.SysLog;
import com.artmall.manager.common.utils.HttpContextUtils;
import com.artmall.manager.sys.pojo.SysLogs;
import com.artmall.manager.sys.pojo.SysUser;
import com.artmall.manager.sys.service.SysLogService;
import com.google.gson.Gson;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description: 系统日志，切面处理类
 * @Author: MING
 * @Eamil lmm_work@163.com
 * @Date: 2018/11/29 16:33
 */
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.artmall.manager.common.annotation.SysLog)")
    public void logPointCut(){
        System.out.println("********   --进入 SysLog 注解--  ********");
    }

    @Around("logPointCut()")//Around注解声明意味着环绕，环绕的对象是自定义注解作用的对象要执行的方法，执行之前和执行之后
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, time);

        return result;
    }

    public void saveSysLog(ProceedingJoinPoint joinPoint, long time){

        // 获取目标方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获得切入的方法
        Method method = signature.getMethod();

        SysLogs sysLogs = new SysLogs();
        SysLog sysLog = method.getAnnotation(SysLog.class);
        if(sysLog != null){
            //注解上的描述
            sysLogs.setOperation(sysLog.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLogs.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        try{
            String params = new Gson().toJson(args[0]);
            sysLogs.setParams(params);
        }catch (Exception e){

        }

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLogs.setIp(IPUtils.getIpAddr(request));

        //用户名
        String username = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getUsername();
        sysLogs.setUsername(username);

        sysLogs.setTime(time);
        sysLogs.setCreateDate(new Date());
        //保存系统日志
        sysLogService.insert(sysLogs);
    }


}
